package com.study_security.controller;

import com.study_security.domain.LoginUser;
import com.study_security.entity.Project;
import com.study_security.entity.SysLog;
import com.study_security.service.ExportService;
import com.study_security.service.ProjectService;
import com.study_security.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/api/export")
public class ExportController {

    @Autowired
    private ProjectService projectService;

    @Autowired
    private ExportService exportService;

    @Autowired
    private SysLogService sysLogService;

    /**
     * 审核用的，可以看到所有的项目
     *
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAuthority('perm_review')")
    @GetMapping("/all/excel")
    public ResponseEntity<byte[]> exportProjectsToExcel() throws IOException {
        List<Project> projects = projectService.getAllProjects();
        byte[] data = exportService.exportProjectsToExcel(projects);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "project.xlsx");

        return ResponseEntity.ok().headers(headers).body(data);
    }

    /**
     * 用户用的（项目负责人）
     * @param authentication
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAuthority('perm_leader')")
    @GetMapping("/user/excel")
    public ResponseEntity<byte[]> exportProjectsToExcel(Authentication authentication) throws IOException {
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        String userName = loginUser.getUser().getUserName();
        List<Project> projects = projectService.getAllProjectByUserId(userId);
        byte[] data = exportService.exportProjectsToExcel(projects);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String fileName = userName + "_project.xlsx";
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok().headers(headers).body(data);
    }

    /**
     * 根据过滤条件导出项目
     *
     * @param authentication
     * @param endDateAfter      结束日期在指定日期之后
     * @param startDateAfter    启动日期在指定日期之后
     * @param contractAmountGt  合同金额大于指定值
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAuthority('perm_review') or hasAuthority('perm_leader')")
    @GetMapping("/filtered/excel")
    public ResponseEntity<byte[]> exportFilteredProjectsToExcel(
            Authentication authentication,
            @RequestParam(required = false) String endDateAfter,
            @RequestParam(required = false) String startDateAfter,
            @RequestParam(required = false) BigDecimal contractAmountGt
    ) throws IOException {
        List<Project> projects;

        if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("perm_review"))) {
            // 如果是审核权限，则导出所有符合条件的项目
            projects = projectService.getFilteredProjects(endDateAfter, startDateAfter, contractAmountGt);
        } else if (authentication.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals("perm_leader"))) {
            // 如果是项目负责人权限，则只导出该用户的符合条件的项目
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            Long userId = loginUser.getUser().getId();
            projects = projectService.getFilteredProjectsByUserId(userId, endDateAfter, startDateAfter, contractAmountGt);
        } else {
            // 无权限
            return ResponseEntity.status(403).build();
        }

        byte[] data = exportService.exportProjectsToExcel(projects);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String fileName = "filtered_project.xlsx";
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok().headers(headers).body(data);
    }

    /**
     * 审核用来导出日志记录
     * @return
     * @throws IOException
     */
    @GetMapping("/logs")
    @PreAuthorize("hasAuthority('perm_review')")
    public ResponseEntity<byte[]> exportLogs() throws IOException {
        List<SysLog> logs = sysLogService.list(); // 获取所有日志数据，您可以根据需求添加过滤条件
        byte[] bytes = exportService.exportLogsToExcel(logs);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        // 设置文件名及编码
        headers.setContentDispositionFormData("attachment", "sys_logs.xlsx");
        headers.setContentLength(bytes.length);

        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }
}
